/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmContractService
 * 项目合同
 * <p>
 * 修改纪录
 * 2020-05-16 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-16
 */
package com.topscomm.pm.service.impl;

import com.itextpdf.text.Paragraph;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboApprovalFlowInsEntity;
import com.topscomm.cbo.service.impl.CboApprovalFlowInsService;
import com.topscomm.pm.pojo.PmContractEntity;
import com.topscomm.pm.service.IPmContractService;
import com.topscomm.pm.service.IPmProjectService;
import com.topscomm.pm.service.impl.auto.PmContractServiceAuto;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.tap.common.DatacodeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "pmContractService")
@Scope(value = "singleton")
public class PmContractService extends PmContractServiceAuto implements IPmContractService {
    @Resource(name = "pmProjectService")
    private IPmProjectService PmProjectService;
    @Autowired
    private CboApprovalFlowInsService cboApprovalFlowInsService;

    /**
     * @param entity
     * @throws
     * @author: wushenghong
     * @date: 2020-05-16
     * @description:单号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            String docNo = String.valueOf(arrayId[0]);
            docNo = docNo.substring(0, 6) + docNo.substring(9);
            entity.setValue(PmContractEntity.FieldDocno, docNo);
            //id赋值合同编号
            entity.setValue(PmContractEntity.FieldContractcode, arrayId[0]);
        }
    }

    /**
     * @param
     * @throws
     * @author: wushenghong
     * @date: 2020-06-13
     * @description:合同总金额计算
     * @modify:
     */
    public void updateContractMoneyOfProjectBase(String sourceId, boolean approvalSuccess) {
        PmContractEntity pmContractEntity = this.queryById(sourceId);
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("select sum(NVL(contractmoney,0)) as totalmoney from PmContract where projectid = {0} and state = 9 and id <> {1}", pmContractEntity.getProjectid(), sourceId);
        BigDecimal totalMoney = BigDecimal.ZERO;

        if (approvalSuccess) {
            totalMoney = pmContractEntity.getContractmoney();
        }
        List<Map<String, Object>> contractMoneyList = this.selectExecute(sql.toString());
        if (contractMoneyList.size() > 0) {
            BigDecimal partMoney = (BigDecimal) contractMoneyList.get(0).get("totalmoney");
            totalMoney = totalMoney.add(partMoney);
        }
        // 更新金额
        sql.clear();
        sql.appendSingle("update pmproject set contractmoney = {0} where id = {1}", totalMoney, pmContractEntity.getProjectid());
        this.updateExecute(sql.toString());
    }


    /**
     * @Description:    扫描件审批节点处理合同金额
     * @Author:         wuyuyang
     * @Return:         void
     * @exception:
     * @Date:           23/10/2023 下午5:39
     * @Version:        1.0
     **/
    public void updateContractMoneyOfProjectBaseForApproval(String sourceId, boolean approvalSuccess) {
        PmContractEntity pmContractEntity = this.queryById(sourceId);
        // 查询出对应流程实例，确认当前走的是那条审批流程
        StringBufferProxy tempSql = new StringBufferProxy();
        tempSql.appendSingle("sourceid = '{0}' and sourcetype = 'PmContract'", sourceId);
        CboApprovalFlowInsEntity cboApprovalFlowInsEntity = cboApprovalFlowInsService.queryObjectByWhere(tempSql.toString());

        StringBufferProxy sql = new StringBufferProxy();
//        sql.appendSingle("select sum(nvl(a.contractmoney, 0)) as totalmoney from pmcontract a inner join cboapprovalnodeins b on a.id = b.sourceid where a.projectid = {0} and b.state = 2 and b.sourcetype = 'PmContract' and b.nodeid = (select id from cboapprovalnode where approvalparam like '%ScannedCopy%' and flowid = '{2}') and a.id <> {1}", pmContractEntity.getProjectid(), sourceId, ConvertUtil.convertToString(cboApprovalFlowInsEntity.getFlowid()));
        sql.appendSingle("select sum(nvl(a.contractmoney, 0)) as totalmoney from pmcontract a inner join cboapprovalnodeins b on a.id = b.sourceid where a.projectid = {0} and b.state = 2 and b.sourcetype = 'PmContract' and exists (select id from cboapprovalnode where approvalparam like '%ScannedCopy%' and flowid = '{2}' and id = b.nodeid ) and a.id <> {1}", pmContractEntity.getProjectid(), sourceId, ConvertUtil.convertToString(cboApprovalFlowInsEntity.getFlowid()));
        BigDecimal totalMoney = BigDecimal.ZERO;

        if (approvalSuccess) {
            totalMoney = pmContractEntity.getContractmoney();
        }
        List<Map<String, Object>> contractMoneyList = this.selectExecute(sql.toString());
        if (contractMoneyList.size() > 0) {
            BigDecimal partMoney = (BigDecimal) contractMoneyList.get(0).get("totalmoney");
            totalMoney = totalMoney.add(partMoney);
        }
        // 更新金额
        sql.clear();
        sql.appendSingle("update pmproject set contractmoney = {0} where id = {1}", totalMoney, pmContractEntity.getProjectid());
        this.updateExecute(sql.toString());
    }

    /**
     * @description: 扫描件审批通过之后 对scannedCopyApprovalTime字段赋值
     * @author: duzehou
     * @date: 2022/11/9 9:32
     * @param: [sourceId, approvalSuccess]
     * @return: void
     **/
    public void scannedCopyApprovalTime(String sourceId, boolean approvalSuccess) {
        SimpleDateFormat dfLong = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time = dfLong.format(new Date());;
        String scannedCopyApprovalTime = SQLAdapter.toDateLong(time);
        PmContractEntity pmContractEntity = this.queryById(sourceId);
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("update pmcontract set scannedcopyapprovaltime = {0} where id = {1}", scannedCopyApprovalTime, sourceId);
        this.updateExecute(sql.toString());
    }

    /**
     * @param
     * @throws
     * @author: hdy
     * @date: 2022-11-03
     * @description:查询机会点关联的工程合同
     * @modify:
     */
    @Override
    public List<Map<String, Object>> queryContractByChance(Map<String, Object> paraMap) {
    	List<Map<String, Object>> contractList = this.queryMap(paraMap, "queryMapByChance");
    	return contractList;
    }

   /**
    * @param
    * @throws
    * @author: hdy
    * @date: 2022-12-02
    * @description:查询机会点关联的工程合同进度
    * @modify:
    */
   @Override
   public List<Map<String, Object>> queryContractPhaseByChance(Map<String, Object> paraMap) {
   	List<Map<String, Object>> contractList = this.queryMap(paraMap, "queryContractPhaseByChance");
   	return contractList;
   }

   /**
    * @param
    * @throws
    * @author: hdy
    * @date: 2022-12-02
    * @description:查询机会点关联的工程合同审批进度
    * @modify:
    */
   @Override
   public List<Map<String, Object>> queryContractApprovalPhaseByChance(Map<String, Object> paraMap) {
   	List<Map<String, Object>> contractList = this.queryMap(paraMap, "queryContractApprovalPhaseByChance");
   	return contractList;
   }
}
